/**
 *
 *@author ZhouLan
 *@version 1.0.0
 */

import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import picker from '@ohos.file.picker';
import request from '@ohos.request';
import { Request } from './Requests';

const internalPath = 'internal://cache/'
export class Picker{
  photoPicker:picker.PhotoViewPicker;
  context : common.UIAbilityContext;
  cacheDir:string
  constructor(context:common.UIAbilityContext) {
    this.photoPicker = new picker.PhotoViewPicker
    this.context = context
    this.cacheDir = context.cacheDir
  }
  async selectPhoto(max:number):Promise<request.File[]>{
    let option =new picker.PhotoSelectOptions()
    option.maxSelectNumber=max
    option.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE
    let files:request.File[] = []
    let result =  await this.photoPicker.select(option)
    console.log("file:"+result.photoUris.toString())
    let uris = result.photoUris
    for (let i = 0; i < uris.length; i++) {
      let filename = i+'.png'
      let file = fs.openSync(uris[i],fs.OpenMode.CREATE)
      try{
        fs.copyFileSync(file.fd,`${this.cacheDir}/${filename}`)
      }catch (e){
        console.error(`选择器错误:${e}}`)
      }
      let multipartFile:request.File = {
        //文件名
        filename:filename,
        //提交时的表单项的名称
        name:'goods',
        //文件在缓存目录下的的地址
        uri:internalPath+filename,
        type:'png'
      }
      files.push(multipartFile)
    }
    console.log("files:"+files.toString())
    return files
  }
  changeConfigUrl(url:string){
    // this.uploadConfig.url = url
  }
}